<?php

namespace app\admin\controller;
use think\Controller;

class Base extends Controller {
    public $account;
    public $modelObj;//控制器对应的model变量

    public function _initialize() {
        parent::_initialize();
        //判断用户是否登陆
        $isLogin = $this->isLogin();
        if(!$isLogin){
            return $this->redirect(url('login/index'));
        }

        //实例化控制器对应的model
        try {
            $this->modelObj = model(request()->controller());
        } catch (\Exception $e) {}

    }

    /**
     * 判定是否登陆
     */
    public function isLogin(){
        //获取session
        $user = $this->getLoginUser();
        if($user && $user->id){
            return true;
        }
        return false;
    }

    /**
     * 通过session获取用户信息
     */
    public function getLoginUser(){
        if(!$this->account){
            $account = session('adminAccount','','admin');
        }
        return $account;
    }

    /**
     * 成功之后刷新页面的JS代码
     */
    public function successView(){
        echo "<script type='text/javascript'>
            window.parent.location.reload();
            </script>";
    }


    /**
     * 更改状态函数
     * @param $id 对应的id
     * @param $status 修改的目标状态（-1删除，0下架，1正常）
     */
    public function status($id,$status){
        $validate = validate(request()->controller());
        $data = [
            'id' => $id,
            'status' => $status,
        ];
        if(!$validate->scene('status')->check($data)){
            $this->result($_SERVER['HTTP_REFERER'], 0, 'fail');
        }
        $res = $this->modelObj->save(['status'=>$status],['id'=>$id]);
        if($res){
            $this->result($_SERVER['HTTP_REFERER'], 1, 'success');
        }else{
            $this->result($_SERVER['HTTP_REFERER'], 0, 'fail');
        }
    }

    /**
     * 更新数据
     * @param $data
     */
    public function update($data){
        $res = $this->modelObj->save($data,['id' => intval( $data['id'] ) ]);
        if($res){
            $this->success("更新成功", url('successView'));
        }else{
            $this->error("添加失败！");
        }
    }
}